package cn.fl.system.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.condition.SysRoleQueryCondition;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysRoleService;
import cn.fl.system.vo.SysRoleVO;

/**
 * @Description: 系统角色表 控制层
 */
@Controller
@RequestMapping("/system/sysRole")
public class SysRoleController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SysRoleController.class);

	/**
	 * SysRole 服务层BEAN
	 */
	@Autowired
	private ISysRoleService sysRoleService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载角色列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("system/sysRole/list");
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		BaseLogUtils.info(logger, "toModifyPage", "加载角色修改页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("system/sysRole/modify");
		view.addObject("id", id);
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String roleNmSearch = request.getParameter("roleNmS");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SysRoleQueryCondition qc = new SysRoleQueryCondition();
		//设置查询条件中的系统代码以及组织架构
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		if (StringUtils.isNotEmpty(roleNmSearch)) {
			qc.setRoleNm(roleNmSearch);
		}
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		page.setCondition(qc);

		BaseLogUtils.info(logger, "initList", "初始化角色列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		
		Pager pager = this.sysRoleService.searchListPage(page);
		List<SysRoleVO> list = (List<SysRoleVO>) pager.getResultList();
		ListPageVO<SysRoleVO> listPage = new ListPageVO<SysRoleVO>(list, pager.getTotalCount());
		return listPage;
	}
	/**
	 * 通过组织架构id查询角色列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getRoleByOrgId.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getRoleByOrgId(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String roleNm = request.getParameter("roleName");
		String orgId = request.getParameter("orgId");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		
		SysRoleQueryCondition qc = new SysRoleQueryCondition();
		//设置查询条件中的系统代码以及组织架构
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		if (StringUtils.isNotEmpty(roleNm)) {
			qc.setRoleNm(roleNm);
		}
		if(StringUtils.isNotBlank(orgId)){
			qc.setOrgId(Long.valueOf(orgId));
		}
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		page.setCondition(qc);
		
		BaseLogUtils.info(logger, "getRoleByOrgId", "根据组织架构id查询角色列表.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.sysRoleService.searchListPageByOrgId(page);
		List<SysRoleVO> list = (List<SysRoleVO>) pager.getResultList();
		ListPageVO<SysRoleVO> listPage = new ListPageVO<SysRoleVO>(list, pager.getTotalCount());
		return listPage;
	}
	/**
	 * 通过组织架构id剔除有关联数据查询角色列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getRoleNotInOrgId.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getRoleNotInOrgId(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String roleNm = request.getParameter("roleName2");
		String orgId = request.getParameter("orgId");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		
		SysRoleQueryCondition qc = new SysRoleQueryCondition();
		//设置查询条件中的系统代码以及组织架构
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		if (StringUtils.isNotEmpty(roleNm)) {
			qc.setRoleNm(roleNm);
		}
		if(StringUtils.isNotBlank(orgId)){
			qc.setOrgId(Long.valueOf(orgId));
		}
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		page.setCondition(qc);
		
		BaseLogUtils.info(logger, "getRoleNotInOrgId", "根据组织架构id去除有关联数据查询角色列表.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		
		Pager pager = this.sysRoleService.searchListPageNotInOrgId(page);
		List<SysRoleVO> list = (List<SysRoleVO>) pager.getResultList();
		ListPageVO<SysRoleVO> listPage = new ListPageVO<SysRoleVO>(list, pager.getTotalCount());
		return listPage;
	}

	
	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getById", "获取角色数据,主键参数为空！", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			SysRoleVO vo = this.sysRoleService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取角色数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取角色数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取角色数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取角色数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		SysRoleVO entity = new SysRoleVO();
		try {
			entity = this.getRequestParamForSysRoleAdd(request);
			Long id = this.sysRoleService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增角色数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增角色数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增角色数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		SysRoleVO entity = new SysRoleVO();
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改角色信息,主键参数为空！.ID:"+id, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			entity = this.getRequestParamForSysRoleModify(request);
			entity.setId(Long.valueOf(id));
			boolean success =this.sysRoleService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modify", "修改角色数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改角色数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改角色数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改角色数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 启用
	 */
	@RequestMapping(value = "/enable.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object enable(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_ENABLE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "enable", "启用角色失败,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			
			boolean success = this.sysRoleService.modifyEnAbleById(Long.valueOf(id), BaseConstant.IS_YESNO_YES);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_ENABLE_FAIL);
				BaseLogUtils.info(logger, "enable", "启用角色失败,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "enable", "启用角色成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "enable", "启用角色失败,ID:"+id+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "enable", "启用角色失败,系统错误.ID:"+id+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 禁用
	 */
	@RequestMapping(value = "/disable.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object disable(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_DISABLE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "disable", "禁用角色,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			
			boolean success = this.sysRoleService.modifyDisAbleById(Long.valueOf(id), BaseConstant.IS_YESNO_NO);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DISABLE_FAIL);
				BaseLogUtils.info(logger, "disable", "禁用角色失败,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "disable", "禁用角色成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "disable", "禁用角色失败,ID:"+id+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "disable", "禁用角色失败,系统错误.ID:"+id+".ERROR"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	//**********************私有方法******************//
	/**
	 * 前端参数获取
	 */
	
	private  SysRoleVO getRequestParamForSysRole(HttpServletRequest request)throws BaseException{
		String  roleNm= request.getParameter("roleNm");
		String  roleTypCd= request.getParameter("roleTypCd");
		String  roleRem= request.getParameter("roleRem");
		String roleIsVis = request.getParameter("isVis");
		SysRoleVO sysRoleVO = new SysRoleVO();
		sysRoleVO.setRoleNm(roleNm);
		sysRoleVO.setRoleTypCd(roleTypCd);
		sysRoleVO.setRoleRem(roleRem);
		if(StringUtils.isNotEmpty(roleIsVis) && StringUtils.isNumeric(roleIsVis)){
			sysRoleVO.setIsVis(Integer.valueOf(roleIsVis));
		}else{
			sysRoleVO.setIsVis(BaseConstant.IS_YESNO_YES);
		}
		
		if(StringUtils.isBlank(roleNm) || roleNm.length() > 50){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "全称不能为空,并且长度不能大于50个字符。");
		}
		return sysRoleVO;
	}
	
	/**
	 * 添加角色
	 */
	
	private  SysRoleVO getRequestParamForSysRoleAdd(HttpServletRequest request)throws BaseException{
	
		SysRoleVO sysRoleVO = this.getRequestParamForSysRole(request);
		sysRoleVO.setCrtTm(new Date());
		sysRoleVO.setIsSysDef(BaseConstant.IS_YESNO_NO);
		sysRoleVO.setIsDel(BaseConstant.IS_YESNO_NO);
		sysRoleVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		sysRoleVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
		sysRoleVO.setIsValid(BaseConstant.IS_YESNO_YES);
		return sysRoleVO;
	}
	
	/**
	 * 修改角色
	 */
	
	private  SysRoleVO getRequestParamForSysRoleModify(HttpServletRequest request)throws BaseException{
		SysRoleVO sysRoleVO = this.getRequestParamForSysRole(request);
		sysRoleVO.setMdfTm(new Date());
		sysRoleVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		return sysRoleVO;
	}
}

